package com.juzipi.rabbit.config;

import com.juzipi.rabbit.service.MailService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @Author juzipi
 * @Date 2021/7/17 16:59
 * @Info
 */
@Component
public class ConsumerWithAck {

    @Autowired
    private MailService mailService;

//    @RabbitListener(queues = "TestDeadQueue")
//    @RabbitHandler
//    public void process(Map map, Channel channel, Message message) throws IOException {
//        System.out.println("DirectQueue收到消息并NACK返回: "+map.toString());
//        try {
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
//        } catch (IOException e) {
//            e.printStackTrace();
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
//        }
//    }


//    @RabbitListener(queues = "DeadQueue")
//    @RabbitHandler
//    public void processDead(Map map, Channel channel, Message message) throws IOException {
//        System.out.println("DeadQueue收到消息并ACK返回: "+map.toString());
//        try {
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
//        } catch (IOException e) {
//            e.printStackTrace();
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
//        }
//    }

    @RabbitListener(queues = "MailQueue")
    @RabbitHandler
    public void process(Channel channel, Message message) throws IOException {
        try {
            Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter();
            String resultMessage = converter.fromMessage(message).toString();
            if (resultMessage!=null){
                mailService.sendHtml("1124685815@qq.com");
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
